/**
 * 网络请求（src/utils/request.js）
 * 调用这里封装的网络请求方法，会在请求头中带上用户token和用户user-id,并在网络请求错误时给出相应的处理（未登录-->跳转至登录页面；请求错误-->提示错误信息,当然在请求错误时也可以追加相应的处理代码）
 */

import {Loading, Message} from 'element-ui'
import axios from 'axios'
import qs from 'qs'

export default {
    ajaxPro: (options) => {
        let data = (options.method === 'POST' || options.method === 'post') ? (qs.stringify(options.data || {})) : (options.data || {})
        return new Promise((resolve, reject) => {
            let index
            if (options.isShowLoad) {
                index = Loading.service({text: '正在请求，请稍后'})
            }
            if (typeof options.method === 'undefined') {
                options.method = 'get'
            }
            let config = {
                url: options.url,
                method: options.method,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'token': $.cookie('token') || ''
                }
            }
            if (options.method === 'get' || options.method === 'delete') {
                config.params = data;
            } else {
                config.data = data;
            }
            axios(config).then((response) => {
                if (response.status === 200) {
                    let res = response.data
                    if (!res.status && res.login !== undefined && !res.login) {
                        // 用户token失效，跳转到登录页面
                        top.location.replace('#/login')
                    }
                    if (res.status !== undefined && !res.status) {
                        Message.error((res.msg !== undefined ? (res.msg) : '发生错误') + '-' + (res.exception !== undefined ? (res.exception) : '发生错误'))
                    }
                    resolve(res)
                } else {
                    Message.error('发生错误：' + response.status)
                }
                if (typeof index != 'undefined') {
                    index.close()
                }
            }).catch((error) => {
                if (typeof index != 'undefined') {
                    index.close()
                }
                if (error.request) {
                    console.log(error.request)
                    if(error.request.status === 429){
                        Message.error(error.request.statusText)
                        return false;
                    }
                    let obj = JSON.parse(error.request.response)
                    Message.error('请求错误：' + error.request.status + '｜' + (typeof obj.msg !== undefined ? obj.msg : '') + '-' + (typeof obj.exception !== undefined ? obj.exception : ''))
                    if (!obj.status && obj.login !== undefined && !obj.login) {
                        // 用户token失效，跳转到登录页面
                        top.location.replace('#/login')
                    }
                } else if (error.response) {
                    console.log(error.response.data)
                    console.log(error.response.status)
                    console.log(error.response.headers)
                    Message.error('响应错误：' + error.response.status)
                } else {
                    console.log(error)
                    Message.error(error.message)
                }
                reject(error)
            })
        })
    },
    ajax: (options) => {
        this.a.ajaxPro({
            isShowLoad: options.isShowLoad,
            method: options.method,
            data: options.data
        }).then((res) => {
            if (typeof options.success === 'function') {
                options.success(res)
            }
        }).catch((error) => {
            if (typeof options.fail === 'function') {
                options.fail(error)
            }
        })
    },
    get: (url = '', data = {}, isShowLoad = false) => {
        let t = this
        return new Promise((resolve, reject) => {
            t.a.ajaxPro({
                url: url,
                method: 'get',
                data: data,
                isShowLoad: isShowLoad
            }).then(resolve).catch(reject)
        })
    },
    post: (url = '', data = {}, isShowLoad = false) => {
        let t = this
        return new Promise((resolve, reject) => {
            t.a.ajaxPro({
                url: url,
                method: 'post',
                data: data,
                isShowLoad: isShowLoad
            }).then(resolve).catch(reject)
        })
    },
    delete:(url = '', data = {}, isShowLoad = false)=>{
        let t = this;
        return new Promise((resolve, reject)=>{
            t.a.ajaxPro({
                url: url,
                method: 'delete',
                data: data,
                isShowLoad: isShowLoad
            }).then(resolve).catch(reject);
        });
    },
    isHavePermissions: (url) => {
        let urls = $.cookie('userMenuUrls')
        if (!urls) {
            return false
        }
        return urls.indexOf(url) > -1
    }
}
